All files / src/app/api/admin/workflows/[id] route.ts

97.66% Statements 167/171
90% Branches 36/40
100% Functions 3/3
97.66% Lines 167/171

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 1721x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 1x 1x 3x 3x 3x 2x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 1x 1x 4x 4x 4x 4x 4x 5x     4x 4x 4x 4x 4x 4x 5x 1x 1x 3x 3x 5x 1x 1x 2x 2x 2x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x     5x 1x 1x 5x 5x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 4x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from 'next/server';
import { } from "next-auth";
import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import { Prisma } from "@prisma/client";
import { WorkflowEngine, workflowUpdateSchema } from "@/lib/workflows";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
 
const LOG_CATEGORY = "ADMIN_WORKFLOW_API";
 
interface RouteParams {
  params: Promise<{ id: string }>;
}
 
/**
 * GET /api/admin/workflows/[id]
 * Get a single workflow with details
 */
async function handleGet(_request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const workflowId = parseInt(id);
 
  if (isNaN(workflowId)) {
    throw ApiError.badRequest("Invalid workflow ID");
  }
 
  const workflow = await prisma.marketingWorkflow.findUnique({
    where: { id: workflowId } });
 
  if (!workflow) {
    throw ApiError.notFound("Workflow");
  }
 
  // Get statistics
  const stats = await WorkflowEngine.getWorkflowStats(workflowId);
 
  // Get recent executions
  const recentExecutions = await prisma.workflowExecution.findMany({
    where: { workflowId },
    take: 10,
    orderBy: { startedAt: "desc" },
    include: {
      user: {
        select: { id: true, email: true, name: true } } } });
 
  return successResponse({
    ...workflow,
    stats,
    recentExecutions: recentExecutions.map((exec) => ({
      id: exec.id,
      userId: exec.userId,
      userEmail: exec.user.email,
      userName: exec.user.name,
      status: exec.status,
      currentStep: exec.currentStep,
      startedAt: exec.startedAt,
      completedAt: exec.completedAt,
      errorMessage: exec.errorMessage })) });
}
 
/**
 * PUT /api/admin/workflows/[id]
 * Update a workflow
 */
async function handlePut(request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const workflowId = parseInt(id);
 
  if (isNaN(workflowId)) {
    throw ApiError.badRequest("Invalid workflow ID");
  }
 
  const body = await request.json();
 
  // Validate input
  const validationResult = workflowUpdateSchema.safeParse(body);
  if (!validationResult.success) {
    throw ApiError.validation("Validation failed", validationResult.error.issues);
  }
 
  const validatedData = validationResult.data;
 
  const existing = await prisma.marketingWorkflow.findUnique({
    where: { id: workflowId } });
 
  if (!existing) {
    throw ApiError.notFound("Workflow");
  }
 
  // If activating, require the workflow not be a draft
  if (validatedData.isActive && (existing.isDraft || validatedData.isDraft)) {
    throw ApiError.badRequest("Cannot activate a draft workflow. Publish it first.");
  }
 
  // Increment version if steps are being updated
  const shouldIncrementVersion =
    validatedData.steps !== undefined &&
    JSON.stringify(validatedData.steps) !== JSON.stringify(existing.steps);
 
  // Build update data with proper type handling
  const updateData: Prisma.MarketingWorkflowUpdateInput = {};
 
  if (validatedData.name) updateData.name = validatedData.name;
  if (validatedData.description !== undefined) updateData.description = validatedData.description;
  if (validatedData.trigger) updateData.trigger = validatedData.trigger;
  if (validatedData.triggerConfig !== undefined) {
    updateData.triggerConfig = validatedData.triggerConfig ?? Prisma.DbNull;
  }
  if (validatedData.steps) {
    updateData.steps = validatedData.steps as Prisma.InputJsonArray;
  }
  if (validatedData.isActive !== undefined) updateData.isActive = validatedData.isActive;
  if (validatedData.isDraft !== undefined) updateData.isDraft = validatedData.isDraft;
  if (shouldIncrementVersion) updateData.version = { increment: 1 };
 
  const workflow = await prisma.marketingWorkflow.update({
    where: { id: workflowId },
    data: updateData });
 
  logger.info("Workflow updated", { category: LOG_CATEGORY, workflowId, name: workflow.name });
 
  return successResponse(workflow);
}
 
/**
 * DELETE /api/admin/workflows/[id]
 * Delete a workflow
 */
async function handleDelete(_request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const workflowId = parseInt(id);
 
  if (isNaN(workflowId)) {
    throw ApiError.badRequest("Invalid workflow ID");
  }
 
  // Check for active executions
  const activeExecutions = await prisma.workflowExecution.count({
    where: {
      workflowId,
      status: { in: ["RUNNING", "WAITING"] } } });
 
  if (activeExecutions > 0) {
    throw ApiError.badRequest(
      `Cannot delete workflow: ${activeExecutions} active execution(s)`
    );
  }
 
  await prisma.marketingWorkflow.delete({
    where: { id: workflowId } });
 
  logger.info("Workflow deleted", { category: LOG_CATEGORY, workflowId });
 
  return successResponse({ message: "Workflow deleted successfully" });
}
 
export const GET = withErrorHandling(withAdmin(handleGet));
export const PUT = withErrorHandling(withAdmin(handlePut));
export const DELETE = withErrorHandling(withAdmin(handleDelete));